<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Model;
class UserController extends Controller {
    public function _initialize(){
        if(!isset($_SESSION['admin'])) {
            $this->display('Index/login');
            exit;
        }
    }
    
    public function userList(){
       $this->display('User/user-list');
    }
    
    public function getUser(){
        $data['user_id'] = I('param.user_id', '');
        $Model = M('user');
        if($data['user_id'] == ''){
            $r['data'] = $Model->select();
        }else{
            $r = $Model->where($data)->find();
        }
        
        echo json_encode($r);
    }

    public function updateUser(){
        $data = I('param.');
        $Model = M('user');
        if($data['user_id'] != ''){
            $r = $Model->save($data);
        }
        
        echo json_encode($r);
    }

    public function deleteUser(){
        $data['user_id'] = I('param.user_id', '');
        $Model = M('user');
        if($data['user_id'] != ''){
            $r = $Model->where($data)->delete();
        }
        echo json_encode($r);
    }

    public function updateUserCredit(){
        $data = I('param.');
        $param['user_id'] = $data['user_id'];
        
        $Model = new Model();
        $Model->startTrans();

        //修改用户积分
        if($data['type'] == '0'){
            $r1 = $Model->table('user')->where($param)->setDec('credit', (int)$data['change_credit']);
        }else{
            $r1 = $Model->table('user')->where($param)->setInc('credit', (int)$data['change_credit']);
        }
        
        //添加修改积分日志
        $r2 = $Model->table('admin_credit')->add($data);

        if($r1 && $r2){
            $Model->commit();
        }else{
            $Model->rollback();
        }

        echo json_encode($r1);
    }
}